package pri.black.dogview.controller;

import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import pri.black.dogview.domain.R;

import java.io.*;
import java.util.Arrays;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/media")
public class MediaServerController {
    File baseDir = new File("F:\\KwDownload\\song");
    @GetMapping("list")
    R list(){
        List<String> list = Arrays.stream(baseDir.listFiles()).map(File::getName).toList();
        return R.ok(list);
    }

    @GetMapping("download/{name}")
    void download(@PathVariable("name") String name, HttpServletResponse response) throws IOException {

        File originFile = new File(baseDir.getAbsolutePath() + File.separator + name);
        if (!originFile.exists()) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType("audio/flac");

        BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(originFile));

        ServletOutputStream outputStream = response.getOutputStream();
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);
        byte[] buf = new byte[1024];
        int len = 1;
        while (len > 0) {
            len = inputStream.read(buf);
            if (len < 0) {
                break;
            }
            bufferedOutputStream.write(buf, 0, len);
        }
        inputStream.close();

        log.debug("send finished");
        return;
    }
}
